package com.yiwei.zxp.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.BankListAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ComboPayBean;
import com.yiwei.zxp.api.bean.CreateOrderBean;
import com.yiwei.zxp.api.bean.GoodsPayBean;
import com.yiwei.zxp.api.model.ComboPayModel;
import com.yiwei.zxp.api.model.GoodsPayModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.event.MainPacketEvent;
import com.yiwei.zxp.event.PaySuccessEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.util.lianlian.utils.BaseHelper;
import com.yiwei.zxp.util.lianlian.utils.Constants;
import com.yiwei.zxp.util.lianlian.utils.MobileSecurePayer;
import com.yiwei.zxp.util.lianlian.utils.PayOrder;
import com.yiwei.zxp.view.PacketPayStepDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BankPayMoneyActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;

    @BindView(R.id.txt_booth_order)
    TextView txtBoothOrder;
    @BindView(R.id.txt_u_line)
    TextView txtULine;
    @BindView(R.id.layout_u_line)
    FrameLayout layoutULine;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;

    private Unbinder unbiner;
    private BankListAdapter adapter;
    private String bank_id;
    private ArrayList<String> orderData;
    private int buyType = 0;
    private String combo_id;
    private String payway;
    private float num;
    private String xian_xia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bankcard_pay_money);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        adapter = new BankListAdapter(this);
        adapter.setOnChooseListener(new BankListAdapter.OnChooseListener() {
            @Override
            public void onClick(String id, String name, String bankcard, String icon) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bank_id = id;
                    }
                }, 200);
            }

            @Override
            public void onChooseTips(String dayLimit) {
                Dialog.showDefaultDialog(BankPayMoneyActivity.this, "", "单卡银行日限额" + dayLimit + "元，现剩余额度不足，建议线下支付", "取消", "线下支付", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        new PacketPayStepDilaog(BankPayMoneyActivity.this).setOnChooseListener(new PacketPayStepDilaog.OnChooseListener() {
                            @Override
                            public void onSubmit() {
                                getOrder(combo_id, num + "", xian_xia, Const.PayWay.ULINE);
                            }
                        }).show();
                    }

                    @Override
                    public void cancel() {

                    }
                });
            }
        });
        list.setAdapter(adapter);

        orderData = getIntent().getStringArrayListExtra("data");
        buyType = getIntent().getIntExtra("pay_type", 0);
        if (buyType == Const.PayType.BOOTH_ORDER) {
            txtBoothOrder.setVisibility(View.VISIBLE);
            combo_id = getIntent().getStringExtra("combo_id");
            payway = getIntent().getStringExtra("payway");
            num = getIntent().getFloatExtra("num", 0);
            xian_xia = getIntent().getStringExtra("xian_xia");
            txtBoothOrder.setText("您需要支付展位订单金额" + getIntent().getDoubleExtra("need_money", 0) + "元");
            layoutULine.setVisibility(View.VISIBLE);
            Spanned txt_money = Spans.with(this).
                    font("线下支付", getResources().getDimensionPixelSize(R.dimen.x32), 0xff000000).style(Typeface.BOLD).
                    font("\n银行卡限额或支付金额较大，建议试试线下支付哦", getResources().getDimensionPixelSize(R.dimen.x24), 0xff999999).
                    build();
            txtULine.setText(txt_money);
            adapter.setMoneyLimit(getIntent().getDoubleExtra("need_money", 0));
        } else {
            txtBoothOrder.setVisibility(View.GONE);
            layoutULine.setVisibility(View.GONE);
        }
        txtRight.setVisibility(View.VISIBLE);
        txtRight.setText("添加");
        txtTitle.setText("银行卡");


    }

    @Override
    protected void onResume() {
        super.onResume();
        getBankCard();
    }

    private void goLLPay(GoodsPayModel.DatasBean item) {
        PayOrder order = null;
        order = constructGesturePayOrder(item);
        String content4Pay = BaseHelper.toJSONString(order);

        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持

        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.pay(content4Pay, mHandler,
                Constants.RQF_PAY, this, false);
    }

    private void goBoothLLPay(ComboPayModel.DatasBean item) {
        PayOrder order = null;
        order = constructBoothGesturePayOrder(item);
        String content4Pay = BaseHelper.toJSONString(order);

        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持

        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.pay(content4Pay, mHandler,
                Constants.RQF_PAY, this, false);
    }


    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");

                        // 成功
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                            EventBus.getDefault().post(new PaySuccessEvent());
                            EventBus.getDefault().post(new MainPacketEvent());

                            ToastUtil.makeText(BankPayMoneyActivity.this, "支付成功");
                            if (buyType == Const.PayType.BOOTH_ORDER) {
                                Util.startActivity(BankPayMoneyActivity.this, MyOrderActivity.class);
                            } else {
                                Util.startActivity(BankPayMoneyActivity.this, BuyerOrderActivity.class);
                            }
                            finish();
                        } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                            // TODO 处理中，掉单的情形
                            String resulPay = objContent.optString("result_pay");
                            if (Constants.RESULT_PAY_PROCESSING
                                    .equalsIgnoreCase(resulPay)) {

                            }
                            ToastUtil.makeText(BankPayMoneyActivity.this, "正在处理中");
                        } else {
                            // TODO 失败
                            ToastUtil.makeText(BankPayMoneyActivity.this, "支付失败");
                            if (buyType == Const.PayType.BOOTH_ORDER) {
                                showDilaog();
                            }
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };

    }

    private PayOrder constructBoothGesturePayOrder(ComboPayModel.DatasBean item) {
        PayOrder order = new PayOrder();
        order.setBusi_partner(item.busi_partner);
        order.setNo_order(item.no_order);
        order.setDt_order(item.dt_order);
        order.setName_goods(item.name_goods);
        order.setNotify_url(item.notify_url);
        // TODO MD5 签名方式
        // TODO RSA 签名方式
        order.setSign_type(item.sign_type);
        order.setCard_no(item.card_no);
        order.setMoney_order(item.money_order);
        order.setUser_id(item.user_id);
        order.setAcct_name(item.card_idno);
        order.setRisk_item(item.risk_item);
        order.setOid_partner(item.oid_partner);
        order.setAcct_name(item.card_idno);
        // TODO MD5 签名方式, 签名方式包括两种，一种是MD5，一种是RSA 这个在商户站管理里有对验签方式和签名Key的配置。

        order.setSign(item.sign);
        return order;
    }

    private PayOrder constructGesturePayOrder(GoodsPayModel.DatasBean item) {
        PayOrder order = new PayOrder();
        order.setBusi_partner(item.busi_partner);
        order.setNo_order(item.no_order);
        order.setDt_order(item.dt_order);
        order.setName_goods(item.name_goods);
        order.setNotify_url(item.notify_url);
        // TODO MD5 签名方式
        // TODO RSA 签名方式
        order.setSign_type(item.sign_type);
        order.setCard_no(item.card_no);
        order.setMoney_order(item.money_order);
        order.setUser_id(item.user_id);

        order.setRisk_item(item.risk_item);
        order.setOid_partner(item.oid_partner);

        // TODO MD5 签名方式, 签名方式包括两种，一种是MD5，一种是RSA 这个在商户站管理里有对验签方式和签名Key的配置。

        order.setSign(item.sign);
        return order;
    }


    public void getBoothPay(String bankcard_id, ArrayList<String> order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ComboPayBean bean = new ComboPayBean();
        bean.bankcard_id = bankcard_id;
        bean.order_no = order_no.get(0);


        Api.api_service.getComboPay(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    ToastUtil.makeText(this, "去支付");
                    goBoothLLPay(result.datas);
                });
    }


    public void getGoodsPay(String bankcard_id, ArrayList<String> order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodsPayBean bean = new GoodsPayBean();
        bean.bankcard_id = bankcard_id;
        bean.order_no = order_no;


        Api.api_service.getGoodsPay(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    goLLPay(result.datas);
                });
    }


    public void getBankCard() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getBankCardList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    bank_id = "";
                    adapter.update(result.datas);
                    if (adapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                        layoutULine.setVisibility(View.GONE);
                        btnSubmit.setText("立即添加");
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                        if (buyType == Const.PayType.BOOTH_ORDER) {
                            layoutULine.setVisibility(View.VISIBLE);
                        }
                        btnSubmit.setText("确定使用");
                    }

                });
    }

    //    创建展位订单
    public void getOrder(String combo_id, String num, String payway, String enName) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        CreateOrderBean bean = new CreateOrderBean();
        bean.combo_id = combo_id;
        bean.num = num;
        bean.pay_way = payway;
        Api.api_service.getCreateOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (enName.equals(Const.PayWay.ULINE)) {
                        Util.startActivity(BankPayMoneyActivity.this, MyOrderActivity.class);
                        finish();
                    } else if (enName.equals(Const.PayWay.UNION)) {

                        ArrayList<String> request_data = new ArrayList<String>();
                        request_data.add(result.datas.order_number);
                        orderData = request_data;
                        getBoothPay(bank_id, orderData);
                    }


                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @Override
    public void onBackPressed() {
        if (buyType == Const.PayType.BOOTH_ORDER) {
            if (orderData != null && orderData.size() != 0) {
                showDilaog();
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    private void showDilaog() {
        Dialog.showDefaultDialog(this, "", "订单24小时内会自动取消喔，您确定要离开吗？", "残忍离开", "继续支付", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {
                Util.startActivity(BankPayMoneyActivity.this, MyOrderActivity.class);
                finish();
            }
        });
    }

    @OnClick({R.id.txt_right, R.id.btn_back, R.id.btn_submit, R.id.layout_u_line})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_u_line:
//                Util.startActivity(this, BankCardAddActivity.class);
                new PacketPayStepDilaog(this).setOnChooseListener(new PacketPayStepDilaog.OnChooseListener() {
                    @Override
                    public void onSubmit() {
                        getOrder(combo_id, num + "", xian_xia, Const.PayWay.ULINE);
                    }
                }).show();

                break;
            case R.id.txt_right:
                Util.startActivity(this, BankCardAddActivity.class);
                break;
            case R.id.btn_back:
                if (buyType == Const.PayType.BOOTH_ORDER) {
                    if (orderData != null && orderData.size() != 0) {
                        showDilaog();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
                break;
            case R.id.btn_submit:
                if (UI.toString(btnSubmit).equals("确定使用")) {
                    if (TextUtils.isEmpty(bank_id)) {
                        ToastUtil.makeText(this, "请选择银行卡");
                        return;
                    }
                    if (buyType == Const.PayType.BUYER_ORDER) {
                        getGoodsPay(bank_id, orderData);
                    } else {
                        if (orderData != null && orderData.size() != 0) {
                            getBoothPay(bank_id, orderData);
                        } else {
                            getOrder(combo_id, num + "", payway, Const.PayWay.UNION);
                        }

                    }
                } else if (UI.toString(btnSubmit).equals("立即添加")) {
                    Util.startActivity(this, BankCardAddActivity.class);
                }

                break;
        }
    }
}
